<template>
  <div ref="aieditor" style="height: 600px" />

  <t-dialog
    v-model:visible="visible"
    :header="t('pages.attachement.choose')"
    width="1000"
    @confirm="dialogConfirm"
    @close="dialogHide"
  >
    <attachement ref="attachementRef" is-diaog />
  </t-dialog>
</template>

<script lang="ts" setup>
import 'aieditor/dist/style.css';

import { AiEditor } from 'aieditor';
import { MessagePlugin } from 'tdesign-vue-next';
import { onMounted, onUnmounted, ref, watch } from 'vue';

import { t } from '@/locales';
import { useLocale } from '@/locales/useLocale';
import Attachement from '@/pages/content/attachement/index.vue';

import { kr } from './kr';
import { tw } from './tw';

const { locale } = useLocale();

const baseUrl = import.meta.env.VITE_API_URL;
const attachementRef = ref();

const model = defineModel<string>();

const aieditor = ref();
const toolbarKeys = [
  'undo',
  'redo',
  'brush',
  'eraser',
  '|',
  'heading',
  'font-family',
  'font-size',
  '|',
  'bold',
  'italic',
  'underline',
  'strike',
  'link',
  'code',
  'subscript',
  'superscript',
  'hr',
  'todo',
  'emoji',
  '|',
  'highlight',
  'font-color',
  '|',
  'align',
  'line-height',
  '|',
  'bullet-list',
  'ordered-list',
  'indent-decrease',
  'indent-increase',
  'break',
  '|',
  'image',
  'quote',
  'code-block',
  'table',
  '|',
  'printer',
  'fullscreen',
];

let aiEditor: AiEditor | null = null;

watch(model, (val) => {
  aiEditor.setContent(val);
});

onMounted(async () => {
  aiEditor = new AiEditor({
    element: aieditor.value as Element,
    i18n: {
      kr,
      tw,
    },
    toolbarKeys,
    placeholder: '...',
    textSelectionBubbleMenu: {
      enable: true,
      items: ['Bold', 'Italic', 'Underline', 'Strike', 'code', 'comment'],
    },
    image: {
      customMenuInvoke: () => {
        dialogShow();
      },
    },
    onBlur: (editor: AiEditor) => {
      model.value = editor.getHtml();
    },
  });

  console.log('locale', locale);
  const langMap: Recordable = {
    zh_CN: 'zh',
    zh_TW: 'tw',
    en_US: 'en',
    ko_KR: 'kr',
  };
  aiEditor.changeLang(langMap[locale.value]);
});

const visible = ref(false);

const dialogShow = () => {
  visible.value = true;
};
const dialogHide = () => {
  visible.value = false;
};
const dialogConfirm = async () => {
  const checkVal = attachementRef.value.getChecked();
  if (!checkVal) {
    MessagePlugin.info(t('common.chooseOne'));
  }
  dialogHide();

  aiEditor.focus().insert(`<img src="${baseUrl}${checkVal.url}">`);
};

onUnmounted(() => {
  // eslint-disable-next-line no-unused-expressions
  aiEditor && aiEditor.destroy();
});
</script>
